package api

import (
	"github.com/dgrijalva/jwt-go"
	"strconv"
	"strings"
	"time"
	"weiboxs.com/new_h_glasses/enums"
	"weiboxs.com/new_h_glasses/models"
	"weiboxs.com/new_h_glasses/utils"
)

type ApiLoginController struct {
	ApiBaseController
}

func(c *ApiLoginController) ApiDoLogin() {
	//c.EnableXSRF = true
	username := strings.TrimSpace(c.GetString("username"))
	userpwd := strings.TrimSpace(c.GetString("password"))
	if len(username) == 0 || len(userpwd) == 0 {
		c.jsonResult(enums.JRCodeFailed, "请填写用户名密码", userpwd)
	}
	userpwd = utils.String2md5(userpwd)
	user, err := models.BackendUserOneByUserName(username, userpwd)
	if user != nil && err == nil {
		if user.Status == enums.Disabled {
			c.jsonResult(enums.JRCodeFailed, "用户被禁用，请联系管理员", "")
		}
		claims := make(jwt.MapClaims)
		claims["uid"] = strconv.Itoa(user.Id)
		claims["username"] = username
		claims["mobile"] = user.Mobile
		claims["realname"] = user.RealName
		claims["departmentid"] = strconv.FormatInt(user.DepartmentId, 10)

		claims["exp"] = time.Now().Add(time.Hour * 480).Unix() //20天有效期，过期需要重新登录获取token
		token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims) //转换token
		tokenString, err := token.SignedString([]byte(jwtKey))  //密钥加密
		if err != nil {
			c.jsonResult(enums.JRCodeFailed, "登录失败，请重试", "")
			return
		}
		//获取用户信息
		c.jsonResult(enums.JRCodeSucc, "登录成功", map[string]string{"accessToken":tokenString, "uid":claims["uid"].(string),"realname":claims["realname"].(string) } )
	} else {
		c.jsonResult(enums.JRCodeFailed, "用户名或者密码错误", "")
	}
}

//验证权限
func(c *ApiLoginController) ApiCheckAuth() {
	auth := c.GetString("auth")
	c.checkAuthor(auth)
	c.jsonResult(enums.JRCodeSucc, "ok", "")
}